package com.eam.handler;

import com.basis.utils.CodeGenerateRuleUtil;
import com.eam.data.EamSpareparts;
import com.eam.data.EamSparepartsCollar;
import com.mes.data.EmesProcessOpr;
import com.mes.data.EmesVendor;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;
import org.openbravo.model.common.enterprise.Locator;
import org.openbravo.model.common.enterprise.Organization;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 设备备品配件入库
 */
public class SparepartAddsbuttonHandler extends BaseActionHandler {
	
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//处理时间格式

	@Override
	protected JSONObject execute(Map<String, Object> parameters, String content) {
		JSONObject jsonRep = new JSONObject();
		String meg = "";
		try {
			JSONObject request = new JSONObject(content);

			jsonRep.put("flag", true);

			JSONArray jsonIds = request.getJSONArray("dateParam");
			
			JSONObject reqData = null;
			String batchs = CodeGenerateRuleUtil.getCode("Eam_Spareparts_Collar", "batch");   //获取批次条码
			
			for (int i = 0;i < jsonIds.length();i ++) {
				reqData = jsonIds.getJSONObject(i);
				
				String resultId = reqData.getString("PlanIds");  //获取行ID
				String code = reqData.getString("ASN_CODE");  //获取物料编码
				String Master = reqData.getString("M_Locator");		//获取库位
				String company = reqData.getString("company");		//获取单位
				String quantitys = reqData.getString("quantity");		//获取入库数量
				String prices = reqData.getString("prices");		//获取价格
				String org = reqData.getString("adorg");		//获取车间			
				String GUCODE = reqData.getString("processopr");		//获取工序
				//String SBCODE = reqData.getString("SBCODE");		//获取设备
				String Supplier = reqData.getString("M_USER");		//获取供应商
				String remarks = reqData.getString("remarks");		//获取备注		
				String Remaining = reqData.getString("Remaining");		//获取安全库存数量			
				Date time  =sdf.parse(sdf.format(new Date())); //获取当前系统时间
				
				String type = "added";  //代表入库类型
				
				BigDecimal Safety_Stocks = new BigDecimal(Remaining);
				
				
				//查询当家登录账户的ID
				String userIdtime = SessionInfo.getUserId(); //登录人的ad_user_id
				
				String eql = "select * from ad_user where ad_user_id = ?";
				
				User userIds = (User)OBDal.getInstance().getSession().createSQLQuery(eql).addEntity(User.ENTITY_NAME).setString(0, userIdtime).uniqueResult();
				
				//查询物料清单ID
				String  sql = "select * from Eam_Spareparts where Eam_Spareparts_id  = ? ";
				
				EamSpareparts wlIds = (EamSpareparts)OBDal.getInstance().getSession().createSQLQuery(sql).addEntity(EamSpareparts.ENTITY_NAME).setString(0, resultId).uniqueResult();
				
				//查询库位ID
				String aql = "select * from M_Locator where M_Locator_id = ? ";
				
				Locator kwids = (Locator)OBDal.getInstance().getSession().createSQLQuery(aql).addEntity(Locator.ENTITY_NAME).setString(0, Master).uniqueResult();
				
				//查询设备ID
				//String wql = "select * from Eam_Facilities where code = ? ";
				
				//EamFacilities sbids = (EamFacilities)OBDal.getInstance().getSession().createSQLQuery(wql).addEntity(EamFacilities.ENTITY_NAME).setString(0, SBCODE).uniqueResult();
				
				//查询工序ID
				String yql = "select * from emes_processopr where emes_processopr_id = '"+GUCODE+"' or name = '"+GUCODE+"' ";
				
				EmesProcessOpr process = (EmesProcessOpr)OBDal.getInstance().getSession().createSQLQuery(yql).addEntity(EmesProcessOpr.ENTITY_NAME).uniqueResult();
				
				//查询供应商ID
				String  oql = "select * from Emes_Vendor where code = ? ";
				
				EmesVendor vendor = (EmesVendor)OBDal.getInstance().getSession().createSQLQuery(oql).addEntity(EmesVendor.ENTITY_NAME).setString(0, Supplier).uniqueResult();
				
				//获取选择的车间
				String cql = "select * from ad_org where name = ? ";
				
				Organization adorg = (Organization)OBDal.getInstance().getSession().createSQLQuery(cql).addEntity(Organization.ENTITY_NAME).setString(0, org.toString()).uniqueResult();
				
				int quantity = Integer.parseInt(quantitys);      //转化后的入库数量
		  		
		  		String companys  = "";
		  		
		  		if( company.equals("对")){
					companys= "10";
				}else if( company.equals("个")){
					companys= "20";
				}else if( company.equals("根")){
					companys= "30";
				}else if( company.equals("盒")){
					companys= "40";
				}else if( company.equals("卷")){
					companys= "50";
				}else if( company.equals("块")){
					companys= "60";
				}else if( company.equals("片")){
					companys= "70";
				}else if( company.equals("套")){
					companys= "80";
				}
		  		
		  		
		  		//存物料出入库记录表
		  		
		  		EamSparepartsCollar  record  = new EamSparepartsCollar(); //将入库记录存入出入库表中
		  		
		  		BigDecimal numbers = new BigDecimal(quantity);
		  		
		  		record.setStockNumbers(Safety_Stocks);
		  		record.setOrganization(adorg);
		  		record.setEamSpareparts(wlIds);
		  		record.setLocator(kwids);
		  		record.setCompany(companys);
		  		record.setNumbers(numbers);
		  		if(!prices.equals("")){
		  			
		  			BigDecimal	jiage = new BigDecimal(prices);
		  			
		  			record.setPrice(jiage);
		  		
		  		}
		  		record.setEmesProcessopr(process);
		  		record.setEmesVendor(vendor);
		  		record.setStorageTime(time);
		  		record.setBatch(batchs);
		  		record.setType(type);
		  		record.setUser(userIds);
		  		record.setRemarks(remarks);
		  		OBDal.getInstance().save(record);
			}

			if(meg.equalsIgnoreCase("")){
				jsonRep.put("flag", true);
				jsonRep.put("message", "处理成功");
				OBDal.getInstance().commitAndClose();
			}else{
				jsonRep.put("flag", false);
				jsonRep.put("message",meg);
				OBDal.getInstance().rollbackAndClose();
			}
			
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
		} finally {
			OBContext.restorePreviousMode();
		}
        
		return jsonRep;
	}
}